package com.xunyin.schedule;

import com.google.gson.Gson;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * Aqara开发者平台接口调用
 */
public class RequestAqara {

    // 项目ID
    private static String appId = "1217432058391597056d5dca";

    // 开发者accessKey
    private static String appKey = "kvo684djt4un2amh1e70cui190p83p5d";

    //appKey对应id
    private static String keyId = "K.1217432058467094530";

    // 接口地址
    private static String endpoint = "https://open-cn.aqara.com/v3.0/open/api";

    private static String accessToken = "79460bf6e202d31eb86481e8cd0ee749";

    private static final MediaType CONTENT_TYPE = MediaType.parse("application/json");

    private static final Gson gson = new Gson();


    public static void main(String[] args) {
/*        String accessToken = "532cad73c5493193d63d367016b98b27";
        String appId = "4e693d54d75db580a56d1263";
        String keyId = "78784564654feda454557";
        String nonce = "C6wuzd0Qguxzelhb";
        String time = "1618914078668";
        String appKey = "gU7Qtxi4dWnYAdmudyxni52bWZ58b8uN";*/
        //String nonce = "C6wuzd0Qguxzelhb";
        //String nonceStr = flattenHeaders.getOrDefault(RequestSignUtils.Constant.NONCE_HEADER_NAME, "");

/*        String nonceStr = UUID.randomUUID().toString().replace("-", "");
        String time = System.currentTimeMillis() + "";

        System.out.println("nonceStr:"+nonceStr);
        System.out.println("time:"+time);

        String sign = createSign(accessToken, appId, keyId, nonceStr, time, appKey);
        System.out.println(sign);*/
/*        {
            "data": [
                {
                    "subjectId": "lumi.158d000a9c4293",
                    "options": [
                        "8.0.2007"
                    ]
                }
          ]
        }*/

/*        {
            "data": [
                {
                    "subjectId": "lumi.158d000a9c4293",
                        "options": [
                            "13.1.85"
                        ]
                }
            ]
        }*/

/*        {
            "intent": "query.resource.info",
                "data": {
                    "model": "lumi.ctrl_ln1.es1",
                    "resourceId": "0.13.85"
            }
        }*/
/*        {
            "intent": "query.resource.name",
                "data": {
            "subjectIds": [
                "lumi.158d000a9c4293"
            ]
        }
        }*/
        //String subjectId = "lumi.158d000a9c4293";

/*        {
            "intent": "write.resource.device",
                "data": [
                    {
                    "subjectId": "lumi.158d000488d874",
                        "resources": [
                            {
                                "resourceId": "14.7.111",
                                "value": "1"
                            }
                        ]
                    }
                ]
        }*/

        // String jsonParamStr = "{\"intent\": \"query.resource.name\",\"data\":{\"subjectIds\": [\"lumi.158d000a9c4293\"]}}";
        // System.out.println("response:"+execute(jsonParamStr));

        System.out.println("response:"+executeWriteResourceDevice("lumi.158d0009e19fea","1"));

    }

    /**
     * 更新设备资源（控制设备）
     * 即设备控制或配置
     * 如打开智能插座，即设置plug_status为1,关闭智能插座设置plug_status为0
     * 插座打开/关闭 0:关闭，1:打开
     * @param subjectIds
     * @param plugStatus
     * @return
     */
    public static Object executeWriteResourceDevice(String subjectIds,String plugStatus){

/*        {
            "intent": "write.resource.device",
                "data": [
                    {
                        "subjectId": "lumi.158d000488d874",
                        "resources": [{"resourceId": "14.7.111","value": "1"}]
                    }
                ]
        }*/


        String jsonParamStr = "{\"intent\":\"write.resource.device\",\"data\":[{\"subjectId\":\""+subjectIds+"\",\"resources\":[{\"resourceId\":\"4.1.85\",\"value\":\""+plugStatus+"\"}]}]}";
        return execute(jsonParamStr);

    }

    /**
     * 用于业务接口：携带Token请求
     */
    public static Object execute(String body) {
        try {

            // 验证开发者信息
/*            if (MapUtils.isEmpty(RequestSignUtils.Constant.CONTAINER)) {
                throw new RequestSignUtils.TuyaCloudSDKException("未初始化开发者信息！");
            }*/

            //String url = RequestSignUtils.Constant.CONTAINER.get(RequestSignUtils.Constant.ENDPOINT) + path;
            String url = endpoint;
            Request.Builder request = postRequest(url, body);

/*            if ("GET".equals(method)) {
                request = getRequest(url);
            } else if ("POST".equals(method)) {
                request = postRequest(url, body);
            } else if ("PUT".equals(method)) {
                request = putRequest(url, body);
            } else if ("DELETE".equals(method)) {
                request = deleteRequest(url, body);
            } else {
                throw new RequestSignUtils.TuyaCloudSDKException("Method only support GET, POST, PUT, DELETE");
            }*/

/*            if (customHeaders.isEmpty()) {
                customHeaders = new HashMap<>();
            }*/
            Headers headers = getHeader();
            request.headers(headers);
            // request.url(RequestSignUtils.Constant.CONTAINER.get(RequestSignUtils.Constant.ENDPOINT) + getPathAndSortParam(new URL(url)));
            Response response = doRequest(request.build());
            return gson.fromJson(response.body().string(), Object.class);
        } catch (Exception e) {
            throw new RequestSignUtils.TuyaCloudSDKException(e.getMessage());
        }
    }

    /**
     * 处理post请求
     */
    public static Request.Builder postRequest(String url, String body) {
        Request.Builder request;
        try {
            request = new Request.Builder()
                    .url(url)
                    .post(RequestBody.create(CONTENT_TYPE, body));
        } catch (IllegalArgumentException e) {
            throw new RequestSignUtils.TuyaCloudSDKException(e.getMessage());
        }

        return request;
    }

    /**
     * 执行请求
     */
    public static Response doRequest(Request request) {
        Response response;
        try {
            response = getHttpClient().newCall(request).execute();
        } catch (IOException e) {
            throw new RequestSignUtils.TuyaCloudSDKException(e.getMessage());
        }
        return response;
    }

    // 获取 http client
    private static OkHttpClient getHttpClient() {
        OkHttpClient client = new OkHttpClient();
        //client.connectTimeoutMillis(connTimeout, TimeUnit.SECONDS);
        //client.setReadTimeout(readTimeout, TimeUnit.SECONDS);
        //client.setWriteTimeout(writeTimeout, TimeUnit.SECONDS);

        return client;
    }

    /**
     * 生成header
     *
     * //@param accessToken 是否需要携带token
     * //@param headerMap   自定义header
     */
    public static Headers getHeader() throws Exception {

        Headers.Builder hb = new Headers.Builder();

/*        Map<String, String> flattenHeaders = flattenHeaders(headerMap);
        String t = flattenHeaders.get("t");
        if (StringUtils.isBlank(t)) {
            t = System.currentTimeMillis() + "";
        }*/

        String nonceStr = UUID.randomUUID().toString().replace("-", "");
        String time = System.currentTimeMillis() + "";
        String sign = createSign(accessToken, appId, keyId, nonceStr, time, appKey);

        hb.add("Accesstoken", accessToken);
        hb.add("Appid", appId);
        hb.add("Keyid", keyId);
        hb.add("Nonce", nonceStr);
        hb.add("Time", time);
        hb.add("Sign", sign);
        hb.add("Lang", "zh");

/*        hb.add(SING_HEADER_NAME, flattenHeaders.getOrDefault(SING_HEADER_NAME, ""));
        String nonceStr = flattenHeaders.getOrDefault(RequestSignUtils.Constant.NONCE_HEADER_NAME, "");
        hb.add(RequestSignUtils.Constant.NONCE_HEADER_NAME, flattenHeaders.getOrDefault(RequestSignUtils.Constant.NONCE_HEADER_NAME, ""));
        String stringToSign = stringToSign(request, body, flattenHeaders);
        if (StringUtils.isNotBlank(accessToken)) {
            hb.add("access_token", accessToken);
            hb.add("sign", sign(RequestSignUtils.Constant.CONTAINER.get(RequestSignUtils.Constant.ACCESS_ID), RequestSignUtils.Constant.CONTAINER.get(RequestSignUtils.Constant.ACCESS_KEY), t, accessToken, nonceStr, stringToSign));
        } else {
            hb.add("sign", sign(RequestSignUtils.Constant.CONTAINER.get(RequestSignUtils.Constant.ACCESS_ID), RequestSignUtils.Constant.CONTAINER.get(RequestSignUtils.Constant.ACCESS_KEY), t, nonceStr, stringToSign));
        }*/
        return hb.build();
    }


    public static String createSign(String accessToken, String appId, String keyId, String nonce, String time, String appKey) {
        // 严格按照Accesstoken、Appid、Keyid、Nonce、Time
        // 顺序拼接为一个string串使用MD5生成签名值，将生成的签名值放在RequestHeader的Sign中；
        StringBuilder sb = new StringBuilder();
        if(StringUtils.isNotBlank(accessToken)){
            sb.append("Accesstoken=").append(accessToken).append("&");
        }
        sb.append("Appid=").append(appId);
        sb.append("&").append("Keyid=").append(keyId);
        sb.append("&").append("Nonce=").append(nonce);
        sb.append("&").append("Time=").append(time).append(appKey);

        String signStr = sb.toString().toLowerCase();
        try {
            return MD5_32(signStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String MD5_32(String sourceStr) throws Exception {
        String result = "";

        try {
            byte[] b = md5(sourceStr.getBytes("UTF-8"));
            StringBuffer buf = new StringBuffer("");

            for(int offset = 0; offset < b.length; ++offset) {
                int i = b[offset];
                if (i < 0) {
                    i += 256;
                }

                if (i < 16) {
                    buf.append("0");
                }

                buf.append(Integer.toHexString(i));
            }

            result = buf.toString();
        } catch (NoSuchAlgorithmException var6) {
            var6.printStackTrace();
        }

        return result;
    }

    private static byte[] md5(byte[] bytes) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(bytes);
        return md.digest();
    }





}
